import pyautogui
import time
import keyboard  # 用于检测按键退出

# ====================== 配置项 ======================
# 第一页需要点击的坐标 (x, y)
# 请根据实际屏幕位置修改这些值
FIRST_PAGE_COORDS = (1215, 381)

# 第二页需要点击的坐标 (x, y)
SECOND_PAGE_COORDS = (1408, 655)

# 点击间隔时间（秒），根据页面切换速度调整
CLICK_INTERVAL = 0.05

# 退出按键（按此键停止脚本）
EXIT_KEY = 'esc'


# ===================================================

def get_screen_resolution():
    """获取屏幕分辨率"""
    screen_width, screen_height = pyautogui.size()
    print(f"屏幕分辨率: {screen_width}x{screen_height}")
    return screen_width, screen_height


def validate_coordinates(x, y, screen_width, screen_height):
    """验证坐标是否在屏幕范围内"""
    if not (0 <= x <= screen_width and 0 <= y <= screen_height):
        print(f"警告: 坐标 ({x}, {y}) 超出屏幕范围!")
        return False
    return True


def main():
    print("坐标点击脚本启动...")
    print(f"按 {EXIT_KEY} 键停止脚本")

    # 获取并显示屏幕分辨率
    screen_width, screen_height = get_screen_resolution()

    # 验证坐标有效性
    validate_coordinates(*FIRST_PAGE_COORDS, screen_width, screen_height)
    validate_coordinates(*SECOND_PAGE_COORDS, screen_width, screen_height)

    # 初始状态：在第一页
    on_first_page = True
    click_count = 0

    try:
        while True:
            # 检查是否按下退出键
            if keyboard.is_pressed(EXIT_KEY):
                print("\n检测到退出按键，脚本停止")
                break

            # 根据当前页面选择要点击的坐标
            if on_first_page:
                x, y = FIRST_PAGE_COORDS
                page_name = "第一页"
            else:
                x, y = SECOND_PAGE_COORDS
                page_name = "第二页"

            # 执行点击
            pyautogui.click(x, y)
            click_count += 1
            print(f"第 {click_count} 次点击: {page_name} ({x}, {y})")

            # 切换页面状态
            on_first_page = not on_first_page

            # 等待指定时间
            time.sleep(CLICK_INTERVAL)

    except Exception as e:
        print(f"发生错误: {str(e)}")


if __name__ == "__main__":
    # 提示用户如何获取坐标
    print("提示: 运行脚本前，请先确定点击坐标:")
    print("1. 打开命令提示符/终端")
    print("2. 输入 python 进入Python交互模式")
    print("3. 输入 import pyautogui 然后输入 pyautogui.displayMousePosition()")
    print("4. 移动鼠标到需要点击的位置，记录显示的x和y坐标")
    print()

    # 安装keyboard库（如果未安装）
    try:
        import keyboard
    except ImportError:
        print("正在安装必要的库...")
        import subprocess
        import sys

        subprocess.check_call([sys.executable, "-m", "pip", "install", "keyboard"])
        import keyboard

    main()
